<script setup>
	import {
		reactive,
		nextTick
	} from 'vue'
	import {
		jumpTo,
		getSex
	} from '@/utils/common'

	import {
		onLoad
	} from '@dcloudio/uni-app'

	import http from '@/api/userAPI'
	import cosUpload from '@/utils/upload'

	import {
		useStore
	} from "@/stores/index"


	const data = reactive({
		code: '',
		name: '',
		sex: '',
		avatar: '/static/icon/avatar.png',
		vallid: false,
	})

	onLoad(() => {
		// 监听从裁剪页发布的事件，获得裁剪结果
		uni.$on('uAvatarCropper', (path) => {

			uni.getFileSystemManager().readFile({
				filePath: path,
				encoding: 'base64',
				success: r => {
					// console.log(r.data, 'base64');
					const fileName = `${uni.$u.guid()}.jpg`; // 指定文件名

					const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`; // 拼接文件路径
					uni.getFileSystemManager().writeFile({
						filePath,
						data: r.data, //上面的base64
						encoding: 'base64',
						success: async () => {
							// console.log('写入文件成功', filePath); //http://usr/test.jpg

							const res = await new cosUpload({
								path: filePath
							}).uploadFile()
							data.avatar = res.url

							// console.log(res)
						}
					})

				}
			})




			// data.avatar = path;
			// 可以在此上传到服务端
			// uni.uploadFile({
			// 	url: 'http://www.example.com/upload',
			// 	filePath: path,
			// 	name: 'file',
			// 	complete: (res) => {
			// 		console.log(res);
			// 	}
			// });


			// uni.downloadFile({
			//   url: tempFilePath,
			//   success: async function (res1) {
			// 	var filePath = res1.tempFilePath;

			// 	const res = await new cosUpload({
			// 		path: filePath
			// 	}).uploadFile()
			// 	data.avatar = res.url

			// 	console.log(res1)

			// 	console.log(res)
			//   }
			// });



		})

	})

	// 上传头像
	function upload() {
		// uni.chooseImage({
		// 	count: 1, //默认9
		// 	sourceType: ['album'], //从相册选择
		// 	success: async function(response) {
		// 		const res = await new cosUpload(response.tempFiles[0]).uploadFile()
		// 		data.avatar = res.url
		// 	},
		// })

		uni.navigateTo({
			url: "/pages/u-avatar-cropper/u-avatar-cropper?destWidth=300&rectWidth=200&fileType=jpg"
		});




	}

	async function confirm() {
		data.vallid = !data.code || !data.name || !data.sex || !data.avatar

		if (!data.code) {
			uni.showToast({
				title: '请输入您的专属代码',
				icon: 'none',
				duration: 2000
			});
			return false;
		}

		if (!data.name) {
			uni.showToast({
				title: "请输入您的真实姓名",
				icon: 'none',
				duration: 2000
			});

			return false;
		} else {

			//用户填写不能超4个字，不能数字符号等


		}

		if (!data.sex) {
			uni.showToast({
				title: "请选择您的性别",
				icon: 'none',
				duration: 2000
			});

			return false;
		}

		if (!data.avatar) {
			uni.showToast({
				title: "请上传您的头像",
				icon: 'none',
				duration: 2000
			});

			return false;
		}

		// 登录
		if (!data.vallid) {
			const res = await http.setUserinfo(data).catch(err => {
				uni.showToast({
					title: err.msg,
					icon: 'none',
					success: () => {

					},
				})
			})
			console.log('🚀 ~ confirm ~ res:', res)

			const userStore = useStore()

			uni.showToast({
				title: res.msg,
				icon: 'none',
				success: () => {


					//登陆后先清除用户缓存
					userStore.user.clear()

					setTimeout(() => {
						jumpTo('/pages/index/index')
					}, 800)
				},
			})

		}
	}

	function handleInput(event) {
		// 过滤掉数字和符号
		let value = event.target.value.replace(/[^a-zA-Z\u4e00-\u9fa5]/g, '');
		// 限制输入长度为4个字
		if (value.length > 4) {
			value = value.slice(0, 4);
		}

		nextTick(() => {
			data.name = value;
		})

	}

	function unLogin() {
		uni.reLaunch({
			url: '/pages/login/index'
		});
	}
</script>

<template>
	<view style="height: 16.312%" />
	<text class="logo">IVMCR</text>
	<text class="title"> 个体专属定制室Individual exclusive customization room </text>
	<input class="input phone" :class="{ isEmpty: data.vallid && !data.code }" v-model="data.code"
		placeholder="请输入您的专属代码（必填）" />
	<text class="tip">Please enter your uniaue code</text>
	<input class="input phone name" :class="{ isEmpty: data.vallid && !data.name }" v-model="data.name"
		@input="handleInput" placeholder="真实姓名 我们在定制过程中如何称呼（必填）" />
	<text class="tip">Real Name</text>
	<!-- 性别 -->
	<view class="sex" :class="{ isEmpty: data.vallid && data.sex == '' }">
		<text class="sex0 male" :class="{ isActive: data.sex === '1' }" @click="data.sex = '1'">男</text>
		<text class="sex0 female" :class="{ isActive: data.sex === '2' }" @click="data.sex = '2'">女</text>
	</view>
	<!-- 上传 -->
	<view class="upload">
		<view class="avatar" @click="upload">
			<image class="pic" v-if="!!data.avatar" :src="data.avatar" mode="aspectFill" />
			<image v-else src="/static/icon/upload.png" mode="aspectFit" />
		</view>
		<text class="tip">请点击+号上传头像</text>
	</view>
	<view class="login" @click="confirm">
		<text>确认</text>
		<image src="@/static/icon/btn-down.png" mode="aspectFit" />
	</view>

	<view style="text-align: center;padding-top: 60rpx;">

		<text @click="unLogin"
			style="padding: 10rpx 40rpx; color:#AAAAAA;font-size: 22rpx;font-weight: 500;border:0.5rpx solid #eee;border-radius: 11rpx;">返回登陆首页</text>
	</view>
</template>

<style lang="scss" scoped>
	.logo {
		display: block;
		color: rgb(0, 0, 0);
		font-size: 30rpx;
		font-weight: 600;
		line-height: 42rpx;
		letter-spacing: 10rpx;
		text-align: center;
	}

	.title {
		margin-top: 21rpx;
		margin-bottom: 88rpx;
		align-self: center;
		width: 242rpx;
		color: rgb(0, 0, 0);
		font-size: 15rpx;
		font-weight: 500;
		line-height: 19rpx;
		text-align: center;
	}

	.name {
		margin-top: 43rpx;
	}

	.sex {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 42rpx auto 0;
		padding: 0 20rpx;
		box-sizing: border-box;
		width: 377rpx;
		height: 100rpx;
		box-sizing: border-box;
		border-radius: 17rpx;

		&.isEmpty {
			border: 1rpx solid rgb(239, 232, 118);
		}

		.sex0 {
			width: 145rpx;
			height: 61rpx;
			box-sizing: border-box;
			border: 0.5rpx solid rgb(225, 225, 225);
			border-radius: 11rpx;
			background: rgb(242, 242, 242);
			color: rgb(180, 180, 180);
			font-size: 20rpx;
			font-weight: 500;
			line-height: 60rpx;
			text-align: center;

			&.isActive {
				background-color: #fff;
				color: #000;
			}
		}
	}

	.upload {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		padding-left: 20rpx;
		width: 377rpx;
		margin: 53rpx auto 0;

		.tip {
			margin-top: 0;
		}

		.avatar {
			margin-right: 17rpx;
			position: relative;
			width: 120rpx;
			height: 113rpx;
			box-sizing: border-box;
			border: 0.5rpx solid rgb(225, 225, 225);
			border-radius: 19rpx;
			background: rgb(242, 242, 242);
			overflow: hidden;

			>.pic {
				transform: translate(-50%, -50%);
				width: 100%;
				height: 100%;
				margin: 0;
			}

			>image {
				position: absolute;
				top: 50%;
				left: 50%;
				margin: -11rpx;
				width: 22rpx;
				height: 22rpx;
			}
		}
	}

	.input {
		align-self: center;
		height: 61rpx;
		box-sizing: border-box;
		border: 0.5rpx solid rgb(225, 225, 225);
		border-radius: 11rpx;
		background: rgb(242, 242, 242);
		color: rgb(180, 180, 180);
		font-family: PingFang;
		font-size: 20rpx;
		font-weight: 500;
		line-height: 19rpx;
		text-align: center;

		&.isEmpty {
			border: 1rpx solid rgb(239, 232, 118);
		}
	}

	:deep(.input-placeholder) {
		font-family: PingFang;
		color: rgb(180, 180, 180);
		font-size: 20rpx;
		font-weight: 500;
		line-height: 19rpx;
		text-align: center;
	}

	.is-hover {
		background: #333;
	}

	.tip {
		margin-top: 17rpx;
		color: rgb(180, 180, 180);
		font-size: 20rpx;
		font-weight: 500;
		line-height: 1;
		text-align: center;
	}

	.phone,
	.code-box {
		width: 443rpx;
	}

	.login {
		position: relative;
		align-self: center;
		margin-top: 113rpx;
		width: 190rpx;
		height: 54rpx;
		filter: drop-shadow(0px 2rpx 1rpx rgba(0, 0, 0, 0.2));

		>image {
			width: 100%;
			height: 100%;
			// box-shadow: 0px 2rpx 1rpx 0 rgba(0, 0, 0, 0.2);
			// filter: drop-shadow(0px 2rpx 1rpx rgba(0, 0, 0, 0.2));
		}

		>text {
			position: absolute;
			width: 100%;
			color: rgb(165, 165, 165);
			font-size: 22rpx;
			font-weight: 500;
			line-height: 54rpx;
			text-align: center;
			z-index: 1;
		}
	}
</style>